// pages/biz/ticket-check.js
const auth = require('../../utils/auth.js');
const bizOrder = require('../../services/bizOrder.js');

Page({
  data: {
    code: null,
    checkStatus: 'pending', // pending, success, fail
    checkMsg: '',
    ticketInfo: null,
    userInfo: null,
    loginReady: false,
    isLoggedIn: false,
  },

  async onLoad(query) {
    // 1. 解析 code
    let q = decodeURIComponent(query.q || '');
    q = decodeURIComponent(q);
    let code = null;
    try {
      const urlObj = new URL(q);
      code = urlObj.searchParams.get('code');
    } catch (e) {
      const match = q.match(/[?&]code=([^&]+)/);
      if (match) code = match[1];
    }
    this.setData({ code });

    // 2. 检查登录状态
    this.checkLoginStatus();
  },

  async checkLoginStatus() {
    try {
      const loginStatus = await auth.checkLoginStatus()

      this.setData({
          isLoggedIn: loginStatus.isLoggedIn,
          userInfo: loginStatus.userInfo,
          loginReady: true
      })

      if (loginStatus.isLoggedIn) {
        // 登录成功后，校验核销码
      this.checkTicket(this.data.code);
    }

      
    } catch (error) {
      this.setData({
        isLoggedIn: false,
        userInfo: null,
        loginReady: true
    })
    }
  },

  async checkTicket(code) {
    this.setData({ checkStatus: 'pending', checkMsg: '', ticketInfo: null });
    try {
      const res = await bizOrder.checkTicket(code);
      if (res.success) {
        this.setData({
          checkStatus: 'success',
          ticketInfo: {
            goodsTitle: res.data.goods_title,
            bizName: res.data.biz_name || '',
            createdAt: res.data.created_at || '',
            expiredAt: res.data.expired_at || '',
            phone: res.data.phone || '',
            status: res.data.status ,
            usedAt: res.data.used_at 
          }
        });
      } else {
        this.setData({
          checkStatus: 'fail',
          checkMsg: res.message || '无权核销'
        });
      }
    } catch (e) {
      this.setData({
        checkStatus: 'fail',
        checkMsg: '网络异常，请稍后重试'
      });
    }
  },

  async onConfirmVerify() {
    if (!this.data.code) {
      wx.showToast({ title: '核销码不能为空', icon: 'none' });
      return;
    }

    // 显示确认对话框
    wx.showModal({
      title: '确认核销',
      content: '确定要核销这个码吗？核销后将无法撤销。',
      success: async (res) => {
        if (res.confirm) {
          // 显示加载提示
          wx.showLoading({ title: '核销中...' });
          
          try {
            const result = await bizOrder.useTicket(this.data.code);
            
            wx.hideLoading();
            
            if (result.success) {
              wx.showToast({ 
                title: '核销成功', 
                icon: 'success',
                duration: 2000
              });
              
              // 更新页面状态
              this.setData({
                checkStatus: 'success',
                checkMsg: '核销成功'
              });

              this.checkTicket(this.data.code);
              
              // 延迟返回上一页
              setTimeout(() => {
                wx.navigateBack();
              }, 2000);
            } else {
              wx.showToast({ 
                title: result.message || '核销失败', 
                icon: 'none' 
              });
            }
          } catch (error) {
            wx.hideLoading();
            wx.showToast({ 
              title: '网络异常，请稍后重试', 
              icon: 'none' 
            });
          }
        }
      }
    });
  },

  onAutoLoginComplete(isLoggedIn, userInfo) {
    
    this.setData({
        isLoggedIn: isLoggedIn,
        userInfo: userInfo,
        loginReady: true
    });

    // 登录状态更新后重新加载VIP状态
    if (isLoggedIn) {
        this.checkTicket(this.data.code);
    }
},

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    if (this.data.loginReady) {
      this.checkLoginStatus();
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})